package com.julu.o2o.util;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 由于ice数据实体没有get/set方法 需要实现属性拷贝，需要重新封装方法
 * 
 * @author yangtonggan
 * @date 2016-3-11
 *
 */
public class BeanUtil {

	/**
	 * 复制数组到List中
	 * 
	 * @param t1
	 * @param orig
	 * @return
	 */
	public static <T1, T2> List<T1> array2List(Class<T1> t1, T2[] orig) {
		List<T2> list = Arrays.asList(orig);
		return copyList(t1, list);
	}

	/**
	 * 复制List中数据到另一个List中
	 * 
	 * @param t1
	 * @param orig
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <T1, T2> List<T1> copyList(Class<T1> t1, List<T2> orig) {
		List<T1> list = new ArrayList<T1>();
		try {
			for (T2 m : orig) {
				Object dest = t1.newInstance();
				BeanUtil.copyProperties(dest, m);
				list.add((T1) dest);
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return list;

	}

	/**
	 * javaBean属性值拷贝
	 * 空串和null值不进行拷贝
	 * @param dest
	 * @param orig
	 */
	public static void copyProperties(Object dest, Object orig) {
		try {
			Class<?> c = orig.getClass();
			Field field[] = c.getDeclaredFields();
			Class<?> c1 = dest.getClass();
			for (Field f : field) {
				String name = f.getName();
				f.setAccessible(true);
				Object value = f.get(orig);
				try {					
					Field f1 = c1.getField(name);
					f1.setAccessible(true);
					f1.set(dest, value);
				} catch (Exception e) {
					continue;
				}

			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}

	}
	
	/**
	 * 把java中的数据复制到Ice模型中
	 * @param model
	 * @param bean
	 */
	public static void bean2Model(Object model, Object bean){
		try {		
			PropertyDescriptor[] origDescriptors = PropertyUtils.getPropertyUtils().getPropertyDescriptors(bean);
			for (int i = 0; i < origDescriptors.length; i++) {
                String name = origDescriptors[i].getName();
                if ("class".equals(name)) {
                    continue; 
                }
                try {
                    Object value = PropertyUtils.getPropertyUtils().getSimpleProperty(bean, name);
                    if(StringUtil.notEmpty(value)){
                    	PropertyUtils.copyProperty(model, name, value);
                    }                    
                } catch (NoSuchMethodException e) {  
                	continue; 
                }
	        }
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

}
